package com.im.server.common.utils;

import com.im.server.common.config.SysCommonConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 描述：获取请求来源的ip地址
 * <p>
 * 作者：HuTongFu
 * 时间：2019/7/12 15:40
 */
public class IPUtils {

    private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

    /**
     * 获取请求IP地址
     * <p>
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        logger.debug("请求来源的IP地址：{}", ip);
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    /**
     * 获取 当前主机的地址
     */
    private static String getLocalhostIp() {
        try {
            //获取的是本地的IP地址
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 获取当前主机uri
     *
     * @return
     */
    public static String getLocalURI() {
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        ServletContext servletContext = request.getServletContext();
        SysCommonConfig sysCommonConfig = (SysCommonConfig) ContextFactoryUtil.getBean("sysCommonConfig");
        if (sysCommonConfig == null || StringUtils.isBlank(sysCommonConfig.getServerUri())) {
            return "http://" + IPUtils.getLocalhostIp() + ":" + request.getServerPort() + servletContext.getContextPath();
        } else {
            return "http://" + sysCommonConfig.getServerUri() + ":" + request.getServerPort() + servletContext.getContextPath();
        }
    }
}
